set_data_custom(formData)
- 由於處理順序是由後面往前,故可設formData={},然後在函式內先設定值,把寫入完成
- 程式碼
/*========================================
設定客戶資料
=========================================*/
function set_data_custom(formData={}) {
let sheet = 'day2';
let ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
let stru = get_stru_custom();
let rowIndex;
// ---------------------------------寫入一筆記錄
rowIndex = ws.getLastRow() + 1;
// 暫時資料
formData = { sn: rowIndex-1, title: 'test', tel: '0123456789', addr: 'aaaa', ps: 'bbbb' };
for (let i in stru) {
let colIndex = Number(i) + 1;//i 型態為字串,須轉為數字做計算
setCellData(sheet, rowIndex, colIndex, formData[stru[i]['form_name']], stru[i]['type']);
}
// ---------------------------------寫入一筆記錄 end
}
- 新增 or 編輯
判斷formData['sn']是否有傳值,有值則是編輯,空值則是新增
新增的列指標 rowIndex = ws.getLastRow() + 1
編輯的列指標
- 取得流水號欄的資料 snData = [1, 2, .......]
- 然後搜尋 snIndex = snData.indexOf(Number(formData.sn))
- snIndex == -1 無此資料,回報錯畫面
- rowIndex = snIndex + 2
- 函式 get_rowIndex(sheet, sn)
/*========================================
取得列指標
找不到 回傳 -1
=========================================*/
function get_rowIndex(sheet, sn){
if(!sheet || !sn)return -1;
let ss = SpreadsheetApp.getActiveSpreadsheet()
let ws = ss.getSheetByName(sheet);
if (ws=== null || ws.getLastRow() < 2) return -1;//尚無資料,返回-1
let colArray = ws.getRange(2, 1, ws.getLastRow() - 1).getValues().map(function(row){
return row[0];
});
let rowIndex = colArray.indexOf(Number(sn));
if(rowIndex !== -1){
rowIndex += 2;
}
return rowIndex;
}
- set_data_custom(formData={})
/*========================================
設定客戶資料
=========================================*/
function set_data_custom(formData={}) {
let sheet = 'day2';
let ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
let stru = get_stru_custom();
let rowIndex;
// 暫時資料
formData = { sn: '4', title: 'test', tel: '0123456789', addr: 'aaaa', ps: 'bbbb' };
// 取得列指標
if(formData.sn){//編輯
rowIndex = get_rowIndex(sheet, formData.sn);
if(rowIndex === -1){
//報錯畫面
}
}else{//新增
rowIndex = ws.getLastRow() + 1;
// 指定流水號
formData.sn = maxSn(sheet);
}
// 寫入工作表
for (let i in stru) {
let colIndex = Number(i) + 1;//i 型態為字串,須轉為數字做計算
setCellData(sheet, rowIndex, colIndex, formData[stru[i]['form_name']], stru[i]['type']);
}
// ---------------------------------寫入一筆記錄 end
}